package com.jule.miaozhuapc.util;

import com.jule.miaozhuapc.controller.wxpayTest.WxCommonUtil;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class WxPayUtil {


    /**
     *  统一支付URL
     */
    private  final  static  String UNI_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    private  final  static  String UTF8 = "UTF-8";

    /**
     *  创建生成订单
     * @return
     * @throws Exception
     */
    public static Object createCharge()throws Exception{
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", Const.WAWA_H5_WX_APPID);// 公众账号id
        parameters.put("mch_id", Const.WAWA_H5_WX_PAY_MCH_ID);// 商户号 1493541142
        parameters.put("nonce_str", YZRandom.createNoncestr(32));// 随机字符串
        parameters.put("body", "测试商家-商品类目");// 商品描述
        parameters.put("detail", "在线购物");// 商品描述
        parameters.put("trade_type", "JSAPI");// 商户订单号
        parameters.put("sign_type", "MD5");// 商户订单号
        parameters.put("fee_type", "CNY");// 商户订单号
        parameters.put("out_trade_no", "20161909105959000000111RT8");// 商户订单号
        parameters.put("total_fee", "1");// 商户订单号
        parameters.put("device_info","WEB");
        parameters.put("notify_url", "https://www.likewawa.com/mzweb");// 支付成功回调地址
        parameters.put("spbill_create_ip", "127.0.0.1");// 商户订单号
        parameters.put("openid", "o0pcH08H7_hINsg9gs1vjiV5aVtc");// 商户订单号

        return "";
    }

    public static void main(String[] args) throws Exception {

        // HostnameVerifier hnv = new HostnameVerifier() {
        //     public boolean verify(String hostname, SSLSession session) {
        //         // Always return true，接受任意域名服务器
        //         return true;
        //     }
        // };
        // HttpsURLConnection.setDefaultHostnameVerifier(hnv);

        String UTF8 = "UTF-8";
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
            parameters.put("appid","wx890410ff186d98b7");// 公众账号id
            parameters.put("mch_id", "1493541142");// 商户号 1493541142
            parameters.put("nonce_str", "b1089cb0231011e7b7e1484520356fdc");// 随机字符串
            parameters.put("body", "测试商家-商品类目");// 商品描述
        parameters.put("detail", "在线购物");// 商品描述
            parameters.put("trade_type", "JSAPI");// 商户订单号
        parameters.put("sign_type", "MD5");// 商户订单号
        parameters.put("fee_type", "CNY");// 商户订单号
        parameters.put("out_trade_no", "20161909105959000000111RT8");// 商户订单号
        parameters.put("total_fee", "1");// 商户订单号
        parameters.put("device_info","WEB");
        parameters.put("notify_url", "https://www.likewawa.com/mzweb");// 商户订单号
        parameters.put("spbill_create_ip", "127.0.0.1");// 商户订单号
        parameters.put("openid", "o0pcH08H7_hINsg9gs1vjiV5aVtc");// 商户订单号


        System.out.println(new JSONObject(parameters));
        String sign = createSignMD5("UTF-8", parameters, "fb1a48fdacf44f7e81819196ab62de49");
        System.out.println(sign);
        String reqBody = "<xml>" +
                "<body>测试商家-商品类目</body>" + //商品简单描述，
                "<openid>o0pcH08H7_hINsg9gs1vjiV5aVtc</openid>" + //用户IopenId
                "<trade_type>JSAPI</trade_type>" +
                "<mch_id>1493541142</mch_id>" +  //商户号
                "<sign_type>MD5</sign_type>" + //签名类型，默认为MD5，支持HMAC-SHA256和MD5。
                "<nonce_str>b1089cb0231011e7b7e1484520356fdc</nonce_str>" +  // 随机字符串，长度要求在32位以内。推荐随机数生成算法
                "<detail>在线购物</detail>" + //商品详细描述
                "<fee_type>CNY</fee_type>" +  //币种 默认RMB
                "<device_info>WEB</device_info>" +  //设备号， pc或公众号内支付可传WEB
                "<out_trade_no>20161909105959000000111RT8</out_trade_no>" + //out_trade_no 商户系统内部订单号
                "<total_fee>1</total_fee>" + //订单总金额，单位为分，详见支付金额
                "<appid>wx890410ff186d98b7</appid>" + //公众号ID appId
                "<notify_url>https://www.likewawa.com/mzweb</notify_url>" + //异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
                "<sign>"+sign+"</sign>" + //通过签名算法计算得出的签名值，详见签名生成算法
                "<spbill_create_ip>127.0.0.1</spbill_create_ip>" + //APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP
                "</xml>";
        URL httpUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
        String UNI_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
       String result = WxCommonUtil.httpsRequestString(UNI_URL, "POST", reqBody);//WxCommonUtil.httpsRequest(WxConstants.UNIFIED_ORDER_URL, "POST", requestXML);

        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setConnectTimeout(10*1000);
        httpURLConnection.setReadTimeout(10*1000);
        httpURLConnection.connect();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(reqBody.getBytes(UTF8));

        //获取内容
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, UTF8));
        final StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String resp = stringBuffer.toString();
        if (stringBuffer!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream!=null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println(resp);
    }

    /**
     *  微信支付 生成sign MD5形式
     * @param characterEncoding  编码格式
     * @param parameters  订单信息
     * @param API_KEY  商户KEY
     * @return
     */
    public static String createSignMD5(String characterEncoding, SortedMap<Object, Object> parameters, String API_KEY) {
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<Object, Object>> es = parameters.entrySet();
        Iterator<Map.Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        /** 支付密钥必须参与加密，放在字符串最后面 */
        sb.append("key=" + API_KEY);
        System.out.println(sb);
        String sign = Md5Encrypt.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }

}
